import { call, put, fork, take } from 'redux-saga/effects'
import { message } from 'antd'
import actions,{ GET_DATA, RESET_PASS_WORD } from '@/actions/main'
import { logout } from './layout'
import api from '@/api/main'
import successDesc from '@/constants/success'

export function* getData() {
  try {
    const { isSuccess, data, desc } = yield call(api.getMainData)
    if(isSuccess) {
      yield put(actions.getDataSuccess(data))
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    message.error(error.message || '获取数据错误')
  }
}

function* resetPassWord() {
  try {
    const { isSuccess, desc } = yield call(api.resetPassWord)
    if(isSuccess) {
      yield put(actions.resetPassWordSuccess())
      message.success(successDesc.resetPassWord)
    }else {
      throw new Error(desc)
    } 
  } catch (error) {
    yield put(actions.resetPassWordFail())
    message.error(error.message || '重置密码错误')
  }
}

function* watchResetPassWord() {
  while(true) {
    yield take(RESET_PASS_WORD)
    yield call(resetPassWord)

    yield call(logout)
  }
}

export function* watchGetData() {
  while(true) {
    yield take(GET_DATA)
    yield call(getData)
  }
}

export default [
  fork(watchGetData),
  fork(watchResetPassWord),
]